#!/usr/bin/python
# -*- coding: utf-8 -*-

from distutils.core import setup
import os,glob,shutil,platform

platformName = platform.system()
if os.name == "posix" and platformName == 'Linux':
    #preparing package
    print 'Building Linux'
    if not os.path.exists("kontrolcu/"):
        shutil.copytree("src/", "kontrolcu/")
        for file in glob.glob("qt4/*"):
            if file[:-3] != "qrc":
                shutil.copy(file, "kontrolcu/")

    from kontrolcu.constants import *

    #removing build files
    def removeBuildFiles():
        rmdir= ["build", "locale", "kontrolcu"]

        for dir in rmdir:
            try:
                print("removing %s"% dir)
                shutil.rmtree(dir)
            except:
                pass

    #creating icons
    def createIcons():
        file = "qt4/icons.qrc"
        file_name = os.path.split(file)[-1]
        os.system("/usr/bin/pyrcc4 %s -o kontrolcu/%s"% (file, file_name.replace(".qrc", "_rc.py")))

    #creating Mo files
    def createMoFiles():
        mo_dir = "locale/"
        os.mkdir(mo_dir)
        datalist=[]
        po_list=glob.glob("po/*.po")
        for file in po_list:
            po_file = os.path.split(file)[-1]
            lang = po_file.split(".")[0]
            mo_file = mo_dir + lang + "/%s.mo"%NAME

            os.mkdir(mo_dir + lang + "/")
            print("%s lang file is generating"% lang)
            os.system("msgfmt %s -o %s"% (file, mo_file))

            datalist.append(("share/locale/%s/LC_MESSAGES"% lang, [mo_file]))

        return datalist

    #Preparing script
    os.rename("%s/%s.py"% (NAME,NAME) , "%s/%s"% (NAME,NAME))
    script = "%s/%s"% (NAME,NAME)
    os.chmod(script, 0755)

    createIcons()

    data = [
        ("share/doc/kontrolcu", ["AUTHORS", "COPYING", "README", "TODO"]),
        ("share/applications", ["data/KontrolcuGui.desktop"]),
        ("kde/4/share/kde4/services/ServiceMenus", ["data/SummaryServMenu.desktop"]),
        ("share/pixmaps", ["data/kontrolcu.png"])]

    data.extend(createMoFiles())

    setup(
        name = NAME,
        version = VERSION,
        description = DESCRIPTION,
        author = CORE_DEVELOPER,
        author_email = CORE_EMAIL,
        url = URL,
        license = LICENSE_NAME,
        packages = [NAME],
        scripts = [script],
        data_files = data,
        )

    #clean build files
    removeBuildFiles()


#building on nt
if os.name == "nt":
    import py2exe
    NAME="kontrolcu"

    #preparing package
    if not os.path.exists("build/"):
        shutil.copytree("qt4\\", "build\\")
        shutil.copy("src\\libkontrolcu.py", "build\\")
        shutil.copy("src\\constants.py", "build\\")
        os.rename("build\\mainqt.py", "build\\kontrolcu.py")

    #creating icons
    def createIcons():
        file = "qt4\\icons.qrc"
        file_name = os.path.split(file)[-1]
        os.system("pyrcc4.exe -o %s %s"% (file_name.replace(".qrc", "_rc.py"), file))
        shutil.copy("icons_rc.py", "build\\")

    #creating Mo files
    def createMoFiles():
        mo_dir = "locale\\"
        os.mkdir(mo_dir)
        datalist=[]
        po_list=glob.glob("po\\*.po")
        for file in po_list:
            po_file = os.path.split(file)[-1]
            lang = po_file.split(".")[0]
            mo_file = mo_dir + lang + os.sep + "%s.mo"%NAME

            os.mkdir(mo_dir + lang + os.sep)
            print("%s lang file is generating"% lang)
            os.system("c:\\python26\\python.exe c:\\python26\\Tools\\i18n\\msgfmt.py -o %s %s"% (mo_file, file))

            datalist.append(("locale\\%s\\LC_MESSAGES"% lang, [mo_file]))

        return datalist


    data=[("",["..\\data\\kontrolcu.png","..\\COPYING.txt"])]
    data.extend(createMoFiles())
    createIcons()
    shutil.copytree("locale", "build\\locale")

    os.chdir("build")
    os.sys.path.append(".\\")

    # To build $python.exe setup.py py2exe
    setup(windows=[{"script" : "kontrolcu.py", }], 
          options={"py2exe" : 
                  {"includes" : ["sip", 
                                 "PyQt4.QtGui",
                                 "PyQt4.QtCore",
                                 "ui",
                                 "dialogs",
                                 "hashlib",
                                 "os",
                                 "gettext",
                                 "urllib",
                                 "sys",],
                   "dll_excludes":["MSVCP90.dll"]}}, 
          data_files=data)

    shutil.copytree("dist", "..\\kontrolcu\\")
    os.chdir("..")
    shutil.rmtree("build")
    shutil.rmtree("locale")
    os.remove("icons_rc.py")
if platformName == 'Darwin':
    import py2app
    NAME="kontrolcu"
    print 'Building on Mac'
    #preparing package
    # To build $python setup.py py2app

    def createIcons():
        file = "qt4/icons.qrc"
        file_name = os.path.split(file)[-1]
        os.system("pyrcc4 -o %s %s"% (file_name.replace(".qrc", "_rc.py"), file))
        shutil.copy("icons_rc.py", "build/")

    if not os.path.exists("build/"):
        shutil.copytree("qt4/", "build/")
        shutil.copy("src/libkontrolcu.py", "build/")
        shutil.copy("src/constants.py", "build/")
        shutil.copy('data/kontrolcu.icns', 'build/')
        os.rename("build/mainqt.py", "build/kontrolcu.py")

    createIcons()
    os.chdir("build")
    os.sys.path.append("./")
    APP = ['./kontrolcu.py']
    OPTIONS = { 'argv_emulation': True, 'iconfile': 'kontrolcu.icns','includes': ["sip", 
                                 "PyQt4.QtGui",
                                 "PyQt4.QtCore",
                                 "ui",
                                 "dialogs",
                                 "hashlib",
                                 "os",
                                 "gettext",
                                 "urllib",
                                 "sys",]}
    setup(
        app=APP,
        options={'py2app': OPTIONS},
        setup_requires=['py2app']
) 
    shutil.copytree('dist/',os.getcwd()[:-5] + 'kontrolcu')
    os.chdir(os.getcwd()[:-5])
    os.sys.path.append('./')
    print 'You need to enter your password here:'
    os.system('sudo rm -r ./build/')
    #os.system('sudo rm -r ./kontrolcu/kontrolcu.app/Contents/Frameworks/QtCore.framework/Versions/')
    #os.system('sudo rm -r ./kontrolcu/kontrolcu.app/Contents/Frameworks/QtGui.framework/Versions/')

    os.system('clear')
    shutil.copy('COPYING.txt','kontrolcu/')

    ask = raw_input('Do you want a .dmg package ?(y/n)\n-> ')
    if ask in ['y','yes']:
        os.system('hdiutil create -imagekey zlib-level=9 -srcfolder kontrolcu/ ./kontrolcu.dmg')
        os.system('sudo rm -r ./kontrolcu/')
    else:
        print '.app file is in \'kontrolcu/\' folder!'
    os.system('sudo rm -r ./icons_rc.py')
    print 'Building is done!'
 
    

